package com.cqan.controller.main;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.cqan.common.ViewModel;
import com.cqan.controller.BaseController;
import com.cqan.entity.account.Permission;
import com.cqan.entity.account.Resource;
import com.cqan.entity.account.User;
import com.cqan.exception.AppException;
import com.cqan.orm.PropertyFilter;
import com.cqan.service.account.PermissionService;
import com.cqan.service.account.ResourceService;
import com.cqan.utils.CodeUtils;

/**
 * 
 * 首页
 * 
 * @author wuhui
 * 
 *         下午01:39:48
 */
@Controller
@RequestMapping("/main")
public class MainController extends BaseController {

	private PermissionService permissionService;

	/**
	 * 加载主页信息(包括左侧菜单)
	 * @return
	 */
	@RequestMapping("/main.htm")
	public ModelAndView main(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView(ViewModel.HOME);
		User user = getUserDetails();
		List<String> authoritys = new ArrayList<String>();
		if (user != null) {
			List<GrantedAuthority> authors = user.getAuthorities();
			for (GrantedAuthority ga : authors) {
				authoritys.add(ga.getAuthority());
			}
		}
		if (authoritys != null && authoritys.size() > 0) {
			List<Permission> permissions = permissionService.getMenusByAuthority(authoritys);
			mv.addObject("reses", obtionJson( obtionResources(permissions)));
		}
		return mv;
	}
	
	//筛选菜单
	public List<Resource> obtionResources(List<Permission> permissions){
		List<Resource>  reses = new  ArrayList<Resource>();
		for (Permission permission : permissions) {
			Resource res = permission.getResource();
			if (res!=null&&res.getType().equals(1)&&res.getParent()==null) {
				reses.add( permission.getResource());
			}
		}
		return reses;
	}

	@RequestMapping("/code.htm")
	public ModelAndView code(HttpServletRequest request,
			HttpServletResponse response) {
		int width = 85;
		int height = 19;
		try {
			BufferedImage image = new BufferedImage(width, height,
					BufferedImage.TYPE_INT_RGB);
			Graphics g = image.getGraphics();
			g.setColor(Color.WHITE);
			g.fillRect(0, 0, width, height);
			g.setFont(new Font("Lucida Console", Font.PLAIN, 18));
			String[] code = CodeUtils.createCode(5, true, true);
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < code.length; i++) {
				g.setColor(CodeUtils.getRandomColor());
				sb.append(code[i]);
				g.drawString(code[i], (int) (width * 0.17) * (i + 1),
						(int) (height * 0.8));
			}
			request.getSession().setAttribute("validateCode", sb.toString());
			logger.debug("validateCode is " + sb.toString());
			g.dispose();
			ServletOutputStream output = response.getOutputStream();
			ImageOutputStream imageOut = ImageIO
					.createImageOutputStream(output);
			ImageIO.write(image, "JPEG", imageOut);
			imageOut.close();
		} catch (IOException e) {
			e.printStackTrace();
			throw new AppException("验证码生成异常!");
		}
		return null;
	}
	
	public String obtionJson(List<Resource> reses){
		
		JSONObject arr = new JSONObject();
		JSONArray array = new JSONArray();
		for (int i=0; i<reses.size();i++) {
			 Resource resource = reses.get(i);
			if (resource!=null&&resource.getParent()==null&&resource.getChildren()!=null&&resource.getChildren().size()>0) {
				JSONObject parent = new JSONObject();
				parent.accumulate("menuid", i+1);
				parent.accumulate("icon",resource.getIcon());
				parent.accumulate("menuname",resource.getName());
				if (resource.getChildren()!=null&&resource.getChildren().size()>0) {
					for (int j = 0; j < resource.getChildren().size(); j++) {
						Resource res = resource.getChildren().get(j);
						JSONObject child = new JSONObject();
						child.accumulate("menuname", res.getName());
						child.accumulate("icon", res.getIcon());
						child.accumulate("url", res.getUrl());
						parent.accumulate("menus", child);
					}
				}
				array.add(parent);
			}
		}
		arr.accumulate("menus",array);
		
		return arr.toString();
	}

	@Autowired
	public void setPermissionService(PermissionService permissionService) {
		this.permissionService = permissionService;
	}

}
